package com.hbnu.service;

import com.hbnu.dao.UserWordBookDAO;
import com.hbnu.dao.WordDAO;
import com.hbnu.entity.UserWordBook;
import com.hbnu.entity.Word;

import java.util.List;

public class UserWordBookService {
    private UserWordBookDAO userBookDAO = new UserWordBookDAO();
    private WordDAO wordDAO = new WordDAO();

    // 创建自定义单词本
    public void createWordBook(int userId, String bookName) {
        if (bookName == null || bookName.trim().isEmpty()) {
            throw new IllegalArgumentException("单词本名称不能为空");
        }

        if (!userBookDAO.createUserWordBook(userId, bookName)) {
            throw new RuntimeException("创建单词本失败，可能名称已存在");
        }
    }

    // 获取用户的所有自定义单词本
    public List<UserWordBook> getUserWordBooks(int userId) {
        List<UserWordBook> books = userBookDAO.getUserWordBooks(userId);
        if (books.isEmpty()) {
            throw new RuntimeException("您还没有创建自定义单词本");
        }
        return books;
    }

    // 向单词本添加单词
    public void addWordToBook(int bookId, int wordId) {
        if (bookId <= 0) {
            throw new IllegalArgumentException("单词本ID必须为正数");
        }
        if (wordId <= 0) {
            throw new IllegalArgumentException("单词ID必须为正数");
        }

        // 检查单词是否存在
        if (wordDAO.getWordById(wordId) == null) {
            throw new RuntimeException("单词不存在");
        }

        if (!userBookDAO.addWordToUserBook(bookId, wordId)) {
            throw new RuntimeException("添加失败，可能单词已在单词本中");
        }
    }

    // 获取单词本中的单词
    public List<Word> getWordsFromBook(int bookId,int userId) {
        if (bookId <= 0) {
            throw new IllegalArgumentException("单词本ID必须为正数");
        }

        List<Word> words = userBookDAO.getWordsFromUserBook(bookId);
        if (words.isEmpty()) {
            throw new RuntimeException("该单词本中没有单词");
        }
        return words;
    }
}